package _01concurrentproblem;

/**
 * 导致并发问题的因素
 * 因素三
 * 编译优化带来的有序性问题
 * <p>
 * 示例: 双重检测的单例模式
 *
 * @author huangy
 * @since 2022/9/13 11:53 上午
 */
public class CompileOptProgram {

    static CompileOptProgram instance;

    static CompileOptProgram getInstance() {
        if (instance == null) {
            synchronized (CompileOptProgram.class) {
                if (instance == null) {
                    instance = new CompileOptProgram();
                }
            }
        }
        return instance;
    }

    public void show() {
        System.out.println("测试双重检测的单例模式");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                synchronized (Thread.class) {
                    CompileOptProgram instance = getInstance();
                    instance.show();
                }
            }

        });
        Thread t2 = new Thread(() -> {
            while (true) {
                synchronized (Thread.class) {
                    CompileOptProgram instance = getInstance();
                    instance.show();
                }
            }
        });
        t1.start();
        t2.start();
    }

}
